package work.marchex;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import utils.MyUtils;

public class Report {

	private static final String marchexLoginUrl = "https://www.voicestar.com/login-1";
	private static final String marchexSessionCookieName = "ATSESS";

	public static void main(String[] args) {
		HttpClient httpclient = null;
		try {
			httpclient = getHttpClient();

			HttpPost loginPost = getLoginRequest();
			HttpResponse loginResponse = httpclient.execute(loginPost);
			String sessionCookie = getMarchexSessionCookie(loginResponse);
			close(loginResponse);

			HttpGet imageGet = getImageRequest(sessionCookie);
			HttpResponse imageResponse = httpclient.execute(imageGet);
			System.out.println(imageResponse.getStatusLine().toString());

			copyToFile(imageResponse.getEntity().getContent());
			close(imageResponse);

		} catch (Exception e) {
			e.printStackTrace(System.out);
		} finally {
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
			}
		}
	}


	private static void close(HttpResponse imageResponse) throws IOException {
		MyUtils.closeQuietly(imageResponse.getEntity().getContent());
	}

	private static void copyToFile(InputStream content) throws IOException {
		Writer wr = new FileWriter("/tmp/a.png");
		MyUtils.copy(content, wr);
	}

	private static HttpGet getImageRequest(String sessionCookie) {
		HttpGet httpGet = new HttpGet("https://www.voicestar.com/clients/report/graphs/clients_pie?acc=QrOX7EXP2OcQYguY;range=7days;start=2012-11-01;end=2012-11-07;size=normal");

//		HttpParams params = new BasicHttpParams();
//		params.setParameter("acc", "QrOX7EXP2OcQYguY");
//		params.setParameter("range", "7days");
//		params.setParameter("start", "2012-11-01");
//		params.setParameter("end", "2012-11-07");
//		params.setParameter("size", "normal");
//
//		httpGet.setParams(params);

		httpGet.setHeader("Cookie", marchexSessionCookieName + "=" + sessionCookie);

		return httpGet;
	}

	private static HttpPost getLoginRequest() throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(marchexLoginUrl);

		List<NameValuePair> postParams = new ArrayList<NameValuePair>();

		postParams.add(new BasicNameValuePair("passwd", "ibcdc11vstar"));
		postParams.add(new BasicNameValuePair("email", "mjones@internetbrands.com"));

		httpPost.setEntity(new UrlEncodedFormEntity(postParams));

		return httpPost;
	}

	private static String getMarchexSessionCookie(HttpResponse response) {
		for (Header header : response.getHeaders("Set-Cookie")) {
			for (HeaderElement headerElement : header.getElements()) {
				if (marchexSessionCookieName.equals(headerElement.getName())) {
					return headerElement.getValue();
				}
			}
		}

		return null;
	}

	public static HttpClient getHttpClient() {
		try {
			HttpClient base = new DefaultHttpClient();
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				@Override
				public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", ssf, 443));
			return new DefaultHttpClient(ccm, base.getParams());
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

}
